package com.free.others;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * <p>
 * Title: Eclipse Plugin Development
 * </p>
 * <p>
 * Description: Free download
 * </p>
 * <p>
 * mail: ganshm@gmail.com
 * </p>
 */

public class ThreadExample
{
    
    public static void main(String[] args)
    {
        
        final Display display = new Display();
        Shell shell = new Shell(display);
        
        // 新建一个线程
        final Runnable print = new Runnable()
        {
            public void run()
            {
                for (int i = 0; i < 100; i++)
                {
                    try
                    {
                        Thread.sleep(100);
                        System.out.println("Print from thread: \t" + Thread.currentThread().getName());
                    }
                    catch (Exception e)
                    {
                        // TODO: handle exception
                    }
                }
            }
        };
        
        shell.setText("Thread Example");
        shell.setSize(300, 100);
        shell.setLayout(new FillLayout());
        Button button = new Button(shell, SWT.CENTER);
        button.setText("asyncExec start");
        button.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                // 线程异步执行
                System.out.println("start");
                display.asyncExec(print);
                System.out.println("stop"); // 不用等待print执行完，就直接执行下面的语句
            }
        });
        
        Button button1 = new Button(shell, SWT.CENTER);
        button1.setText("syncExec start");
        button1.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                // 线程同步执行
                System.out.println("start");
                display.syncExec(print);
                System.out.println("stop"); // 等待print执行完，才执行下面的语句
            }
        });
        
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }
}
